<?php
namespace app\model;

use think\Model;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\cache\driver\Redis;
use think\facade\Cache;
class User extends Model
{
    // protected $name = 'user';
    protected $pk = 'uid';
    // 设置当前模型对应的完整数据表名称
    protected $table = 'ims_users';
    public static $authkey = 'fF2wa4Cn';
    private static $jwt_key = '';
    // public static $key = md5('字符串加密');
    
    // 设置当前模型的数据库连接
    // protected $connection = 'db_config';

    private static function get_key( ){

        if( empty( self::$jwt_key ) ){
            self::$jwt_key = md5( '字符串加密' );
        }

        return self::$jwt_key;
    } 

    /**
     * 用户登录
     */
    public static function login( $username, $password ){

        $user = self::where( 'username' , $username )->find();

        if( empty( $user ) ){
            return [
                'code'      => 1,
                'message'   => '账户或者密码错误',
            ];
        }

        $pwd = self::user_hash( $password, $user->salt );
        
        if($user->password != $pwd ){
            return [
                'code'      => 1,
                'message'   => '账户或者密码错误'
            ];
        }

        $token = self::createToken( $user->uid );
        
        return [
            'code'  => 0,
            'token' => $token,
        ];;
        
    }

    public static function user_hash($passwordinput, $salt) {
        global $_W;
        $authkey = self::$authkey;
        $passwordinput = "{$passwordinput}-{$salt}-{$authkey}";
        return sha1($passwordinput);
    }

    public static function createToken( $user_id, $uniacid = null  ){
        // $key = md5('字符串加密');
        $key = self::get_key();
        // 签发时间
        $time = time();
        // 过期时间
        $expire = $time + 14400;
        // $userId =2;
        $token = [
            'user_id' => $user_id,
            'iss'     => 'www.shenmi.xyz',
            'and'     => '字符串加密',
            'nbf'     => $time,
            'iat'     => $time,
            'exp'     => $expire
        ];

        $jwt = JWT::encode( $token, $key, 'HS256' );

        $redis = Cache::store('redis')->handler();
        // $redis = new Redis();
        //存储数据。存储的数据为序列化的，读出来会自动反序列化，所以不用担心
        // $redis->set('admin-token:' . $user_id, $jwt, 14400);
        
        $redis->hSet('admin::' . $user_id, 'token', $jwt);
        $redis->Hset('admin::' . $user_id, 'uniacid', $uniacid );
        return $jwt;
    }

    public static function checkToken( $token ){

        $key = self::get_key();
        $jwt = JWT::decode( $token, new Key($key,'HS256'));
        if( !$jwt ){
            return [
                'code'=>1,
                'message'=>'没有权限',
            ];
        }
        $jwt = json_encode( $jwt );
        $jwt = json_decode( $jwt, true );

        if( !$jwt || !isset($jwt['user_id']) ){
            return [
                'code'=>2,
                'message'=>'没有权限',
            ];
        }
        $redis = Cache::store('redis')->handler();
        // $redis_token = $redis->get('admin-token:' . $jwt['user_id'] );
        // $redis_token = $redis->get('admin::' . $jwt['user_id'] );
        $redis_token = $redis->hget('admin::' . $jwt['user_id'], 'token' );

        if( !$redis_token ){
            return [
                'code'=>3,
                'message'=>'没有权限',
            ];
        }
        
        // $jwt['code'] = 0;
        
        $res = [
            'code'=>0,
            'user_id'=>$jwt['user_id'],
        ];

        // TODO 获取用户名称， 用户所在店铺
        $sql = 'select * from ims_users where uid=' . $jwt['user_id'];
        $user_info = pdo_fetch( $sql );
        $res['user_name'] = $user_info['username'];

        $uniacid = current_uni_account();
        if( !empty( $uniacid ) ){

            $sql = 'select * from ims_uni_account where uniacid=' . $uniacid;
            $uniAccount= pdo_fetch( $sql );
            
            $res['uniacid'] = $uniacid;
            $res['uniacname'] = $uniAccount ? $uniAccount['name'] : '';
        }
        return $res;
        

    }

    public static function logout( $token ){

        // todo 检查 token的 合法性
        $ret = self::checkToken( $token );

        if( $ret['code'] ){

            return $ret;
        }

        // todo 删除redis中的token信息
        $redis = Cache::store('redis')->handler();
        // $ret['delete'] = $redis->del('admin-token:' . $ret['user_id'] );
        $ret['delete'] = $redis->del('admin::' . $ret['user_id'] );
        return $ret;
    }

    public static function changePassword( $user_id, $current_password, $new_password ){

        $user = self::where( 'uid' , $user_id )->find();
        $pwd = self::user_hash( $current_password, $user->salt );
        
        if($user->password != $pwd ){

            return [
                
                'code'=>1,
                'message'=>'原始密码错误',
            ];
        }
        
        $new_pwd = self::user_hash( $new_password, $user->salt );
        $user->password = $new_pwd;
        $ret = $user->save();

        return [
                
            'code'      => 0,
            'message'   => '原始密码错误',
            'ret'       => $ret,
        ];
    }
}